<template>
  <view class="login-wrap">
    <view class="login-container">
      <!-- 韩国风格装饰元素 -->
      <view class="korean-pattern top"></view>
      <view class="korean-pattern bottom"></view>
      
      <view class="header">
        <image src="/static/logo1.png" class="logo" />
        <view class="title-group">
          <text class="brand-name">韩国落地签拼团</text>
          <text class="slogan">안녕하세요! 一起探索韩国之旅</text>
        </view>
      </view>

      <view class="content">
        <view class="welcome-text">
          <text class="welcome">환영합니다</text>
          <text class="sub-welcome">欢迎加入韩国拼团</text>
        </view>

        <view class="login-options">
          <button
            class="login-btn phone-btn"
            :disabled="!isAgreePrivacy"
            open-type="getPhoneNumber"
            @getphonenumber="handleGetPhoneNumber"
          >
            <image src="/static/dl.png" class="button-image" />
          </button>
          <view class="login-tip">点击按钮快速完成登录</view>
        </view>

        <view class="korean-elements">
          <image src="/static/korean-pattern.png" class="korean-decoration" mode="aspectFit" />
        </view>

        <view class="privacy-agreement">
          <checkbox-group @change="handlePrivacyChange">
            <label class="agreement-label">
              <checkbox :value="isAgreePrivacy" :checked="isAgreePrivacy" color="#FF4B4B" style="transform:scale(0.7)" />
              <text class="agreement-text">我已阅读并同意</text>
              <text class="link" @click.stop="showPrivacyPolicy">《用户服务协议》</text>
              <text class="agreement-text">和</text>
              <text class="link" @click.stop="showPrivacyPolicy">《隐私政策》</text>
            </label>
          </checkbox-group>
        </view>
      </view>
    </view>

    <u-popup
      :show="showPrivacy"
      @close="showPrivacy = false"
      mode="center"
      width="80%"
      height="60%"
      :round="10"
      :closeable="true"
    >
      <view class="privacy-popup">
        <view class="privacy-title">用户服务协议及隐私政策</view>
        <scroll-view class="privacy-content" scroll-y>
          <text class="privacy-text">
            感谢您使用韩国落地签拼团小程序！我们非常重视您的个人信息和隐私保护。
            为了更好地保障您的个人权益，在使用我们的产品前，请您认真阅读《用户服务协议》和《隐私政策》的全部内容...
            【这里填写具体的隐私政策内容】
          </text>
        </scroll-view>
        <view class="privacy-buttons">
          <button class="privacy-btn reject" @click="rejectPrivacy">不同意</button>
          <button class="privacy-btn agree" @click="agreePrivacy">同意</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {login} from "@/api/pt";
import {getToken, setToken} from "@/utils/auth";
import {wxLogin} from "@/utils/api";

export default {
  data() {
    return {
      scene: '', // 存储场景值
      scanParams: {}, // 存储扫码参数
      isAgreePrivacy: false, // 是否同意隐私政策
      showPrivacy: false, // 控制隐私政策弹窗
      loading: false, // 添加loading状态
    }
  },
  onShow() {
    // 检查是否已经登录
    if (getToken()) {
      this.loginSuccess();
    }
  },
  async onLoad(options) {
    try {
      // 获取页面参数
      console.log('页面参数:', options)
      // 获取场景值
      if(options.scene) {
        // scene需要解码
        this.scene = decodeURIComponent(options.scene)

        // 解析场景值中的参数
        try {
          // 假设场景值是key1=value1&key2=value2格式
          const params = {}
          this.scene.split('&').forEach(item => {
            const [key, value] = item.split('=')
            params[key] = value
          })
          this.scanParams = params
          console.log('解析后的扫码参数:', this.scanParams)
        } catch(err) {
          console.log('场景值解析失败:', err)
        }
      }

      // 获取其他url参数
      if(options.q) {
        // 如果是通过二维码扫描进入,q参数会包含完整的url
        const qUrl = decodeURIComponent(options.q)
        try {
          const url = new URL(qUrl)
          this.scanParams = Object.fromEntries(url.searchParams)
          console.log('URL参数:', this.scanParams)
        } catch(err) {
          console.log('URL解析失败:', err)
        }
      }
    } catch (error) {
      console.error('页面加载错误:', error)
    }
  },
  methods: {
    async handleGetPhoneNumber(e) {
      if (this.loading) return;
      
      console.log('获取手机号回调:', e)
      if (!e.detail.code) {
        uni.showToast({
          title: '需要授权手机号才能登录',
          icon: 'none'
        })
        return;
      }

      try {
        this.loading = true;
        await this.handleLogin(e.detail.code);
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    async handleLogin(phoneCode = null) {
      try {
        const loginResult = await new Promise((resolve, reject) => {
          uni.login({
            provider: "weixin",
            onlyAuthorize: true,
            success: resolve,
            fail: reject
          });
        });

        console.log('uni.login成功:', loginResult);
        
        const params = {
          avatarUrl: "",
          code: loginResult.code,
          nickname: ""
        };
        
        console.log('登录参数:', params);
        
        const res = await login(params);
        console.log('登录响应:', res);
        
        const {code, token} = res;
        console.log(code, token,'ce');
        
        if (code === 200 && token) {
          console.log('登录成功');
          setToken(token);
          //本地存储role
          // uni.setStorageSync('role', data.role);
          // uni.setStorageSync('role_id', data.id);
          // uni.setStorageSync('role_name', data.nickName);
          this.loginSuccess();
        } else {
          throw new Error(msg || '登录失败');
        }
      } catch (error) {
        console.error('登录过程出错:', error);
        throw error;
      }
    },
    loginSuccess() {
      console.log('准备跳转页面');
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    // 处理隐私政策勾选
    handlePrivacyChange(e) {
      this.isAgreePrivacy = e.detail.value.length > 0;
    },

    // 显示隐私政策
    showPrivacyPolicy() {
      this.showPrivacy = true;
    },

    // 同意隐私政策
    agreePrivacy() {
      this.isAgreePrivacy = true;
      this.showPrivacy = false;
    },

    // 拒绝隐私政策
    rejectPrivacy() {
      this.isAgreePrivacy = false;
      this.showPrivacy = false;
      uni.showToast({
        title: '需要同意隐私政策才能使用',
        icon: 'none'
      });
    },
  },
}
</script>

<style lang="scss">
.login-wrap {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #FFF5F5 0%, #FFE8E8 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 60rpx 40rpx;
}

.header {
  display: flex;
  align-items: center;
  margin-top: 80rpx;
  padding: 0 20rpx;
}

.logo {
  width: 140rpx;
  height: 140rpx;
  margin-right: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.title-group {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.brand-name {
  font-size: 44rpx;
  font-weight: 700;
  color: #FF4B4B;
  letter-spacing: 2rpx;
}

.slogan {
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: -100rpx;
}

.welcome-text {
  text-align: center;
  margin-bottom: 80rpx;
}

.welcome {
  display: block;
  font-size: 56rpx;
  font-weight: 700;
  color: #FF4B4B;
  margin-bottom: 20rpx;
}

.sub-welcome {
  font-size: 48rpx;
  color: #333;
  font-weight: 600;
}

.login-options {
  padding: 0 30rpx;
}

.login-btn {
  position: relative;
  height: 100rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.3s ease;
  overflow: hidden;
  background: #FF4B4B;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(255,75,75,0.3);
}

.login-btn:active {
  transform: scale(0.98);
}

.login-btn:disabled {
  background: #999;
  opacity: 0.7;
}

.login-tip {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  margin-top: 16rpx;
}

.privacy-agreement {
  margin-top: 30rpx;
  padding: 0 30rpx;
}

.agreement-label {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666;
}

.agreement-text {
  margin: 0 4rpx;
}

.link {
  color: #FF4B4B;
}

.privacy-popup {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.privacy-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20rpx;
  color: #FF4B4B;
}

.privacy-content {
  height: 60vh;
  padding: 20rpx;
}

.privacy-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.privacy-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
  gap: 20rpx;
}

.privacy-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.privacy-btn.reject {
  background: #f5f5f5;
  color: #666;
}

.privacy-btn.agree {
  background: #FF4B4B;
  color: #fff;
}

.button-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
}
</style>
